<?php


namespace FoxLib\Middleware;

use Closure;
use FoxLib\Services\DebugService;
use Illuminate\Http\Request;

class DebugMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (app()->environment('local')) {
            $request->headers->set('X-Authenticated-Userid', 1);
        }
        $response = $next($request);
        $debugInfo = app('debugbar')->collect();
        if (!empty($debugInfo['queries']['nb_statements'])) {
            $count = $debugInfo['queries']['nb_statements'];
            $method = $debugInfo['__meta']['method'];
            $uri = $debugInfo['__meta']['uri'];
            $time = $debugInfo['queries']['accumulated_duration_str'];
            $sql = [];
            foreach ($debugInfo['queries']['statements'] as $statement) {
                unset($statement['backtrace']);
                $sql[] = $statement;
            }
            DebugService::trace($uri, $method, $count, $time, json_encode($sql));
        }

        return $response;
    }
}